<template>
	<x-popup :value="value" mode="bottom" zIndex="999999" @close="$emit('input', false)">
		<view class="shop-class-container">
			<view class="flex-between u-p-b-26">
				<view class="flex-center">
					<view class="shop-class-image clear-flex">
						<x-image :src="showImage(activeAttr.image || dataInfo.imgUrl, 'logo')" :preview="!!activeAttr.image" />
					</view>
					<view class="u-m-l-12 flex-between flex-column">
						<view class="flex-baseline u-lh-42" style="color: #FC2642;">
							<view class="u-f-35">{{ lang_unit.money }}</view>
							<view class="u-f-58">
								{{ activeAttr.discountPrice !== undefined ? activeAttr.discountPrice : (dataInfo.discountPrice || 0) }}
							</view>
						</view>

						<view v-if="dataInfo.allowIntegral" class="u-m-t-18 u-f-28 u-lh-40">
							{{ lang_common.justPayScore[0] }}<text class="font-bold">{{ activeAttr.discountPrice !== undefined ? activeAttr.integral : (dataInfo.integral || 0) }}</text>{{ lang_common.justPayScore[1] }}
						</view>
					</view>
				</view>

				<image src="@/static/image/common/close_grew.png" style="width: 30rpx; height: 28rpx;"
					class="clear-flex" @click="$emit('input', false)"></image>
			</view>

			<!-- 分割线 -->
			<u-gap height="1" bgColor="rgba(151,151,151,.2)"></u-gap>

			<scroll-view scroll-y style="height: 328rpx;" class="u-p-b-34">
				<view class="u-p-t-28">
					<view v-for="(obj, oindex) in dataInfo.goodsSpecList || []" :key="oindex"
						:class="[oindex ? 'u-m-t-38' : '']">
						<view class="u-f-30 u-lh-42 font-medio">{{ obj.name || '' }}</view>

						<view>
							<view v-for="(item, index) in obj.attributeList || []" :key="index" :class="['u-m-t-14 u-m-r-16 u-f-28 u-lh-40',
							`shop-class-item${ actives[oindex] === index ? '-active' : '' }`, (!item.stock || !hasActive(oindex, index, item.id)) ? 'disabled-selected-type' : '']"
								@click="item.stock && hasActive(oindex, index, item.id) && changeActive(oindex, index)">
								{{ item.name || '' }}
							</view>
						</view>
					</view>
				</view>
			</scroll-view>

			<!-- 分割线 -->
			<u-gap height="1" bgColor="rgba(151,151,151,.2)"></u-gap>

			<view class="flex-center-between u-p-t-36 u-p-b-40" style="height: 42rpx;">
				<view class="u-f-30 u-lh-42">{{ lang_goods.number }}</view>

				<view v-if="activeAttr.stock">
					<u-number-box v-model="count" button-size="22" :max="activeAttr.stock"></u-number-box>
				</view>
				<view v-else>{{ lang_goods.notStock }}</view>
			</view>

			<view class="flex-center-center">
				<x-common-btn width="676" @click="changeAction()">
					<view>{{ lang_goods.orderNow }}</view>
				</x-common-btn>
			</view>
		</view>
	</x-popup>
</template>

<script>
	import {
		goodsInfo
	} from '@/api/user/goods.js'
	import {
		cartAddOrUpdate
	} from '@/api/user/shopcart.js'
	export default {
		props: {
			value: {
				type: Boolean,
				default: false
			},

			type: {
				type: String,
				default: 'ready'
			},
			goodsId: {
				default: ''
			}
		},
		data() {
			return {
				dataInfo: {},

				count: 1,

				actives: [],
				
				currentActiveIndex: -1,
				currentActiveAttr: []
			}
		},
		computed: {
			specAttributePriceList() {
				return this.dataInfo.specAttributePriceList || []
			},
			attrIds() {
				let goodsSpecList = this.dataInfo.goodsSpecList || []
				let actives = this.actives || []
				let attrIds = ','
				let currentIds = actives.map((oindex, index) => {
					if (oindex > -1) {
						let {
							attributeList
						} = goodsSpecList[index] || []
						let item = attributeList[oindex] || {}
						attrIds += item.id + ','
					}
				})
				attrIds = attrIds.slice(1, -1)
				return attrIds
			},
			activeAttr() {
				let {
					specAttributePriceList
				} = this || []
				let attrIds = this.attrIds
				let index = specAttributePriceList.findIndex(item => item.attrIds === attrIds)
				return specAttributePriceList[index] || {}
			}
		},
		watch: {
			goodsId: {
				handler(v) {
					!!v && this.initInfo()
				},
				deep: true,
				immediate: true
			}
		},
		methods: {
			// 判断是否存在组合
			hasActive(sindex, aindex, id) {
				// let actives = this.actives
				// if (actives.findIndex(item => typeof item === 'number') > -1) {
				// 	for (let i = 0, alen = actives.length; i < alen; i++) {
				// 		if (i !== this.currentActiveIndex) {
				// 			let aItem = actives[i]
				// 			let alist = this.currentActiveAttr.filter(cItem => cItem.attrIds.split(',').includes(String(id)))
				// 			if (alist.length) return true
				// 		}
				// 	}
				// 	return false
				// }
				return true
			},
			// 产品参数选中后触发
			changeActive(current, index) {
				let currentIndex = this.actives[current] === index ? -1 : index
				this.$set(this.actives, current, currentIndex)
				this.currentActiveIndex = current
				
				let goodsSpecList = this.dataInfo.goodsSpecList || []
				let flist = this.specAttributePriceList
				this.actives.map((aindex, _index) => {
					let currentSpec = goodsSpecList[_index]
					if (currentSpec && currentSpec.attributeList[aindex]) {
						let attrId = currentSpec.attributeList[index].id
						flist = flist.filter(item => item.attrIds.split(',').includes(String(attrId)) && item.stock)
					}
				})
				this.currentActiveAttr = flist
				this.$emit('change', this.activeAttr)
			},
			changeAction() {
				if (!this.activeAttr.stock || !this.count) return
				this.$emit('input', false)
				if (this.type === 'cart') {
					let {
						id,
						desc
					} = this.activeAttr || {}
					// 添加到购物车
					cartAddOrUpdate({
						specs: desc,
						goodsId: this.goodsId,
						amount: this.count,
						type: 1,
						goodsSpecAttributePriceId: id,
						attrIds: this.attrIds
					}).then(() => {
						this.$store.dispatch('initUserData')
					})
				} else if (this.type === 'ready') {
					uni.navigateTo({
						url: `/pages/user/order/ready/ready`,
						success: res => {
							let { goodsType } = this.dataInfo
							res.eventChannel.emit('order-ready', ({
								type: goodsType === 4 ? 'collage' : [5, 7].includes(goodsType) ? 'coupon' : 'goods',
								list: [{
									...this.activeAttr,
									amount: this.count,
									title: this.dataInfo.title,
									specs: this.activeAttr.desc,
									imgUrl: this.activeAttr.image || this.dataInfo.imgUrl
								}]
							}))
						}
					})
				}
			},
			// 预处理规格
			initStockType(obj) {
				let {
					goodsSpecList,
					specAttributePriceList
				} = obj
				let list = goodsSpecList.map(attr => {
					attr.attributeList = attr.attributeList.map((item, index) => {
						item.stock = 0
						specAttributePriceList.map((_item, _index) => {
							if (_item.attrIds.split(',').includes(String(item.id))) {
								item.stock += _item.stock
							}
						})
						return item
					})
					return attr
				})
				return ({
					...obj,
					goodsSpecList: list
				})
			},
			// 初始化详情
			initInfo() {
				goodsInfo({
					goodsId: this.goodsId
				}).then(result => {
					this.dataInfo = this.initStockType(result)
					this.currentActiveAttr = this.specAttributePriceList
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.shop-class {
		&-container {
			padding: 36rpx 38rpx 0;
			border-top-left-radius: 30rpx !important;
			border-top-right-radius: 30rpx !important;
			background-color: #FFFFFF;
			padding-bottom: calc(40rpx + env(safe-area-inset-bottom));
			padding-bottom: calc(40rpx + constant(safe-area-inset-bottom));
		}

		&-image {
			width: 124rpx;
			height: 124rpx;
			border-radius: 4rpx;
			overflow: hidden;
			background-color: #f9f9f9;
		}

		&-item {
			display: inline-block;
			padding: 10rpx 26rpx;
			border-radius: 4rpx;
			color: #999999;
			background-color: #F9F9F9;
			border: 2rpx solid #f9f9f9;

			&-active {
				@extend .shop-class-item;
				color: #FC2642;
				background-color: rgba(252, 38, 66, 0.07);
				border-color: #FC2642;
			}
		}
	}

	.disabled-selected-type {
		color: #333;
		background-color: #ddd;
	}
</style>
